<template>
  <div class="screenRtOne">
    <Title>
      <template #title>
        今日学部各餐次就餐统计
      </template>
    </Title>
    <!-- 动态生成图表容器 -->
    <div v-for="(item, index) in chartDataList" :key="index" v-show="!props.isNodate">
      <div class="chartBox chart" :ref="el => chartRefs[index] = el"></div>
      <div class="tipBox">{{ item.title }}当前：已就餐占比{{ item.total_rate }}%，未就餐占比{{ 100 - item.total_rate }}%</div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { ref, onMounted, nextTick } from 'vue'
import $util from "../util/util"
import * as echarts from 'echarts';
import { PiniaStore } from '../store/index'
import { ElMessage } from 'element-plus'
import { facultyMealtimeStatistic } from './Options/Api'
const store = PiniaStore()
interface PropsType {
  screenRtTwoHeight?: number
  isNodate?: boolean
}
const props = withDefaults(defineProps<PropsType>(), {
  screenRtTwoHeight: 0,
  isNodate: false,
})
// 存储图表实例
const chartInstances = ref<any[]>([])
// 存储图表引用
const chartRefs = ref<any[]>([])
// 存储图表数据和标题
const chartDataList = ref<any[]>([])

const getList = async () => {
  const res: any = await facultyMealtimeStatistic()
  if (res.code !== 1) return ElMessage.error(res.msg)
  // 清空旧数据
  chartDataList.value = []
  disposeAllCharts()
  // 根据接口返回数据动态生成图表配置
  res.data.list.forEach((item: any, index: number) => {
    // 准备图表数据
    const chartData = []
    for (let i = 0; i < 5; i++) {
      chartData.push({
        name: ['早餐', '午餐', '晚餐', '夜宵', '其他'][i],
        value: item[`mealtime_${i + 1}_pay_user_count`],
        rate: item[`mealtime_${i + 1}_rate`]
      })
    }
    // 添加图表配置
    chartDataList.value.push({
      title: item.faculty_name,
      total_rate: item.total_rate,
      data: chartData
    })
    console.log(chartDataList.value, 'chartDataList')
  })

  // 等DOM更新后初始化图表
  await nextTick()
  initAllCharts()
  store.setLoddingStatus()
}
// 初始化所有图表
const initAllCharts = () => {
  chartDataList.value.forEach((chartConfig, index) => {
    if (chartRefs.value[index]) {
      const myChart = echarts.init(chartRefs.value[index])
      chartInstances.value[index] = myChart

      // 图表配置（复用原有配置）
      const option = {
        title: {
          text: chartConfig.title,
          left: '26%',
          top: 'center',
          textStyle: {
            fontSize: $util.fontSize(16),
            color: '#FFFFFF',
            align: 'center'
          },
        },
        legend: {
          orient: 'vertical',
          right: $util.fontSize(30),  //图例距离左的距离
          top: 'center',
          color: "#ffffff",
          itemGap: $util.fontSize(14),
          icon: "rect",
          verticalAlign: 'middle', // 垂直居中对齐
          itemWidth: $util.fontSize(12), // icon宽度
          itemHeight: $util.fontSize(12), // icon高度
          formatter: function (name: any) {
            let target;
            for (let i = 0; i < chartConfig.data.length; i++) {
              if (chartConfig.data[i].name === name) {
                target = chartConfig.data[i].value
              }
            }
            return [// 显式添加图标占位符
              '{e|' + name + '}',
              '{a|' + target + '笔}'
            ].join('');
          },
          textStyle: {
            color: "#fff",
            fontSize: $util.fontSize(14),
            rich: {
              e: {
                fontSize: $util.fontSize(16),
                color: "#ffffff",
                fontWeight: 400,
                verticalAlign: 'middle', // 垂直居中对齐
                padding: [$util.fontSize(4), 0, 0, 0],
                fontFamily: 'HarmonyOS Sans SC',
                lineHeight: $util.fontSize(0),
                width: $util.fontSize(60),
              },
              a: {
                fontSize: $util.fontSize(16),
                color: "#ffffff",
                fontWeight: "bold",
                fontFamily: 'HarmonyOS Sans SC',
                verticalAlign: 'middle', // 垂直居中对齐
                padding: [$util.fontSize(4), 0, 0, 0],
                lineHeight: $util.fontSize(0),
                width: $util.fontSize(60),
              }
            },
          },
        },
        color: ['#11DADE', '#FDAA1B', '#138FFF', '#3951E1', '#B9E8FE'],
        // ... 其他配置保持不变 ...
        series: [
          {
            name: '',
            confine: true,
            type: 'pie',
            left: '-35%',
            radius: ['38%', '80%'],
            center: ['50%', '50%'],
            avoidLabelOverlap: false,
            clockWise: false, // 默认逆时针
            normal: {
              borderWidth: 2,
              borderColor: '#fff'
            },
            itemStyle: {
              borderColor: '#0A1739',
              borderWidth: 1
            },
            label: {
              show: false,
              position: 'center',
              normal: {
                show: false,
                position: 'center',
                rich: {
                  total: {
                    fontSize: $util.fontSize(18),
                    fontFamily: "Arial-Bold, Arial",
                    color: '#ffffff',
                    lineHeight: $util.fontSize(22),
                    fontWeight: 'bold'
                  },
                  active: {
                    fontFamily: "Microsoft YaHei-Bold, Microsoft YaHei",
                    fontSize: $util.fontSize(14),
                    color: '#ffffff',
                    lineHeight: $util.fontSize(22),
                    fontWeight: 'bold'
                  },
                }
              },
              emphasis: {
                show: false
              }
            },
            // ... 其他配置保持不变 ...
            data: chartConfig.data,
          }
        ],
        tooltip: {
          backgroundColor: "#fff",
          borderColor: 'transparent',
          extraCssText: "box-shadow: 0px 9px 28px 1px rgba(0,0,0,0.05);",
          // 添加自定义position函数，让tooltip显示在饼图外部上方
          // position: ['100%', '50%'],
          formatter: function (obj: any) {
            return (
              `<span style="display:flex; justify-content:space-between; margin-bottom: 2px">
                  <span><span style="display:inline-block;font-size:12px;vertical-align: middle;color:#000000;">总人数：</span></span>
                  <span style="display:inline-block;margin-left:20px;font-size:12px;vertical-align: middle;color:#333333;">${chartConfig.data[obj.dataIndex].value}</span>
              </span>` + `<span style="display:flex; justify-content:space-between; margin-bottom: 2px">
                  <span><span style="display:inline-block;font-size:12px;vertical-align: middle;color:#000000;">总金额：</span></span>
                  <span style="display:inline-block;margin-left:20px;font-size:12px;vertical-align: middle;color:#333333;">${chartConfig.data[obj.dataIndex].amount}元</span>
              </span>` + `<span style="display:flex; justify-content:space-between; margin-bottom: 2px">
                  <span><span style="display:inline-block;font-size:12px;vertical-align: middle;color:#000000;">占比：</span></span>
                  <span style="display:inline-block;margin-left:20px;font-size:12px;vertical-align: middle;color:#333333;">${chartConfig.data[obj.dataIndex].rate}%</span>
              </span>`
            )
          },
        },
      }
      myChart.setOption(option)
    }
  })
}
// 销毁所有图表
const disposeAllCharts = () => {
  chartInstances.value.forEach(instance => {
    if (instance) {
      instance.dispose()
    }
  })
  chartInstances.value = []
}

// 重新加载图表
const reloadChart = () => {
  disposeAllCharts()
  initAllCharts()
}

// 修改onMounted
onMounted(async () => {
  window.addEventListener("resize", () => {
    setTimeout(() => {
      reloadChart()
    }, 500)
  });
})
defineExpose({ getList })
</script>
<style lang="scss" scoped>
.screenRtOne {
  height: 524px;
  background: rgba(0, 40, 87, 0.4);

  .chartBox {
    width: 100%;
    height: 200px;
    position: relative;

    .chart {
      width: 100%;
      height: 100%;
      max-height: 250px;
    }
  }

  .tipBox {
    width: 346px;
    height: 32px;
    line-height: 32px;
    background: linear-gradient(180deg, rgba(49, 251, 251, 0.4) 0%, rgba(49, 251, 251, 0) 100%);
    border-radius: 4px;
    margin: auto;
    font-size: 14px;
    color: #29F1FA;
    text-align: center;
  }
}
</style>